package main;

import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;

import java.util.List;

public class GenerateImpl {

    public static final void genWithMethod(PsiClass psiClass, final List<PsiField> selectedFields){

        PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiClass.getProject());
        String className = psiClass.getName();

        //for (PsiField field : psiClass.getFields()) {
        for (PsiField field : selectedFields) {
            String fieldName = field.getName();
            String fieldDataType = field.getType().getPresentableText();
            String methodName = "with" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);

            StringBuilder sb = new StringBuilder();
            sb.append("public "+ className + " " + methodName +"("+ fieldDataType + " " + fieldName +"){");
            sb.append("this." + fieldName + " = " + fieldName + ";");
            sb.append("return this;");
            sb.append("}");

            PsiMember toString = elementFactory.createMethodFromText(sb.toString(), psiClass);
            PsiElement method = psiClass.add(toString);
            JavaCodeStyleManager.getInstance(psiClass.getProject()).shortenClassReferences(method);
            CodeStyleManager.getInstance(psiClass.getProject()).reformat(method);
        }
    }

    public static final void genBuilderMethod(PsiClass psiClass, final List<PsiField> selectedFields){

        PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiClass.getProject());
        String className = psiClass.getName();

        for (PsiField field : selectedFields) {
            String fieldName = field.getName();
            String fieldDataType = field.getType().getPresentableText();
            String methodName = fieldName;//方法名就是属性名

            StringBuilder sb = new StringBuilder();
            sb.append("public "+ className + " " + methodName +"("+ fieldDataType + " " + fieldName +"){");
            sb.append("this." + fieldName + " = " + fieldName + ";");
            sb.append("return this;");
            sb.append("}");

            PsiMember toString = elementFactory.createMethodFromText(sb.toString(), psiClass);
            PsiElement method = psiClass.add(toString);
            JavaCodeStyleManager.getInstance(psiClass.getProject()).shortenClassReferences(method);
            CodeStyleManager.getInstance(psiClass.getProject()).reformat(method);
        }
    }
}
